vue中的vuex

学习vue,你不得不接触vuex。因为你会遇到数据的传送。

在vue世界中,数据的传送分为子传父,父传子,非父子传送

vuex是解决非父子传送的有效方法。

一般来说,我们在需要用到vuex的时候,会在src文件夹下建立一个store子文件夹,在store中有index.js,里面导入vue和vuex,然后使用Vue.use(Vuex)

会定义初始状态,city为要渲染的值

const state = {
city:'  '
}
然后观察数据是同步渲染还是异步渲染
同步写在mutations中,异步写在actions中
const mutations = {
changeCity(state,pickedCity){
state.city = pickedCity
console.log(1)
}
}
最后实例化vuex对象,暴露接口
const store = new Vuex.Store({
state,
mutations
})
export default store
 
 
在项目的根vue中引用
import store from './store/'
 
new Vue({
store,
render: h => h(App)
}).$mount('#app')
 
在共享数据的页面中引入vuex
import { mapState, mapMutations } from 'vuex'
computed: {
...mapState(['city'])
},
methods:{
pickIt (city) {
//进行跳转
this.$router.push('/foot')
console.log(city)
if (city) {
this.$store.commit('changeCity', city)
}
},
在要传值的那个页面传值的地方写入变量
 
import { mapState } from 'vuex'
 
computed: {
...mapState(['city'])
},
 
注意一个坑
不要用router-link进行跳转,会让下面的操作失效
posted @ 2018-11-11 16:51  GJRgjr  阅读(109)  评论(0编辑  收藏  举报