组件公用数据 Vue.observable( )

注意(适合小项目,不用vuex的情况下使用)

1.创建store.js 最好和main.js平级创建文件

import Vue from 'vue'

export const store = Vue.observable({
  name: '李四'
})
export const mutations = {
  setName (data) {
    store.name = data
  }
}

2.在两个组件中调用改写 (如果全局都有使用,也可在mian.js通过Vue.pototype来全局挂载,不用每个组件都引入)

<template>
  <el-row>
    <span @click="findClick">{{data}}</span>
  </el-row>
</template>

<script>
import {store, mutations} from '@/store.js'
export default {
  name: 'mainView',
  data() {
    return {
      data: ''
    }
  },
  mounted() {
    this.data = store.name // 引入store.js 通过定义的store直接获取
  },
  methods: {
    findClick() {
      this.$router.push({path: '/login'})
      mutations.setName('我改了') // 引入store.js 通过定义的mutations下边的方法修改
    }
  }
}
</script>

<style scoped lang="less">
span {
  cursor: pointer;
}
.add {
  pointer-events: none;
}
</style>

猜你喜欢

转载自www.cnblogs.com/wjsy/p/11602182.html