提交 49e34218 编写于 作者: Z zhaoss

2.3.2小节习题、关键字添加

上级 07aa854f
{
"node_id": "vue-0bd1547bbb68451086e3d4b2f4f51f3e",
"keywords": [
"VueX的安装与配置",
"VueX的安装"
],
"children": [],
"export": [
"exercises.json"
],
"keywords_must": [
"VueX"
],
"keywords_forbid": []
}
\ No newline at end of file
{
"type": "code_options",
"author": null,
"source": "exercises.md",
"notebook_enable": false,
"exercise_id": "55859253e09246f5a267f5cf262d2dd0"
}
\ No newline at end of file
# VueX的安装与配置
<div style="color: pink;">小常识:</div>
<br>
**安装**
```javascript
npm i vuex --save
```
**在src文件目录下新建store>index.js文件**
```javascript
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store();
export default store;
```
**入口文件里面引入store,然后再全局注入**
```javascript
import store from './store'//引入store
new Vue({
el: '#app',
router,
store,//使用store
template: '<App/>',
components: { App }
})
```
**使用**
在state中定义数据
```javascript
Vue.use(Vuex)
const store = new Vuex.Store({
state:{
count:1
}
})
```
Getter相当于vue中的computed计算属性,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算,Getters 可以用于监听、state中的值的变化,返回计算后的结果
```javascript
getters:{
getCount:state=>{
return state.count+1
}
```
给action注册事件处理函数,当这个函数被触发时候,将状态提交到mutations中处理。actions里面自定义的函数接收一个context参数和要变化的形参
```javascript
actions:{
addFun(context,n){
context.commit('add',n)
}
removeFun(context){
context.commit("remove")
}
}
```
mutations是一个对象里。面的方法 都是同步事务,是更改state初始状态的唯一合法方法,具体的用法就是给里面的方法传入参数state或额外的参数
```javascript
mutations:{
addstaten){
state.count = state.count+n
},
remove(){
state.count=state.count-1
}
},
```
dispatch:含有异步操作,例如向后台提交数据,写法: this.$store.dispatch('action方法名',值)
commit:同步操作,写法:this.$store.commit('mutations方法名',值)
```javascript
export defult{
data(){
return{
mag:'aaa'
}
},
methods:{
addCount(){
this.$store.commit('add')
},
reoveCount:function(){
this.$store.commit('remove')
},
addFun(){
let n =2;
this.$store.dispatch('addFun',n)
},
removeFun(){
this.$store.dispatch('removeFun')
}
}
}
```
<br>
<div style="color: pink;">小测试:</div >
根据上方资料,以下说法不正确的是?<br/><br/>
## 答案
创建 store 实例之前不需要引入vuex
## 选项
### A
安装完成之后需要创建一个新的 store 实例
### B
Unpkg.com 提供了基于 npm 的 CDN 链接,会一直指向 npm 上发布的最新版本
### C
可以使用 npm 对Vuex进行安装
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册