在vue中使用vuex之state,下面是一个简单的教程,适合新手学习vuex的时候使用。
首先要引入一下vue和vuex,为了方便学习,我就直接在头部引进cdn
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
<script src="https://cdn.bootcss.com/vuex/3.1.1/vuex.js"></script>
</head>
然后我们在script里面创建一个仓库store,然后在state里面存放一个数据count,然后在mutations里面改变这个count
//创建一个仓库
var store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
然后直接使用这个方法,这里调用的四次
store.commit('increment')
store.commit('increment')
store.commit('increment')
store.commit('increment')
接下来就可以在vue中使用这个state了,首先,我们要创建一个vue实例
var app = new Vue({
el: "#app",
store,
})
注意,这个Vue的实例要创建在仓库的后面! 不然会报错的
然后我们就可以在根组件直接引用这个state里面的数据了,代码如下:
<div id="app">
根组件:<div>{{this.$store.state.count}}</div>
</div>
接下来是在组件中使用state,首先创建一个组件,注意这里也要在创建vue实例之前创建,然后我们可以使用state的辅助函数
Vue.component('counter', {
template: `<div>{{count}}</div>`,
computed: Vuex.mapState(['count'])
})
上面mapState的调用其实是下面的缩写
computed: mapState({
messageCount:(state)=> state.messageCount
})
完整代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
<script src="https://cdn.bootcss.com/vuex/3.1.1/vuex.js"></script>
</head>
<body>
<div id="app">
根组件:<div>{{this.$store.state.count}}</div>
子组件:<counter></counter>
</div>
<script>
//创建一个仓库
var store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
store.commit('increment')
store.commit('increment')
store.commit('increment')
store.commit('increment')
// console.log(store.state.count)
Vue.component('counter', {
template: `<div>{{count}}</div>`,
computed: Vuex.mapState(['count'])
})
var app = new Vue({
el: "#app",
store,
})
</script>
</body>
</html>
效果如下: