注意(適合小項目,不用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>