vue 中的Vuex实践

建一个文件夹store 在下面新建一个文件inde.jx

复制代码
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const state={   //要设置的全局访问的state对象
    name: 'beautiful',
    address: 'Hunan Changsha',
    school: '国防科大',
    showFooter: true,
    changableNum:0
    //要设置的初始属性值
  };
  export default new Vuex.Store({
    state
})
复制代码

在main.js 中添加

 

 

import store from './store'
new Vue({
  el: '#app',
  router,
  store, //新加
  components: { App},
  template: '<App/>'
})

页面调用

复制代码
<template>
<el-container>
  <el-header>Header</el-header>
  <!-- <el-main> <my-demo :title="abc" @myclick="fangfayi" ></my-demo> </el-main> -->

  <div>
      第二种方法
      <my-demo :title.sync="abc" >88888888</my-demo>
  </div>

  <br/>
  {{abc}}
  <br/>
  <p/>
  {{countnum}}
  <button @click="testdemo">test</button>
  {{address}}
  <el-footer>Footer</el-footer>
</el-container>
</template>

<script>
import testAVue from './testA.vue';
import MyDemo from '../components/MyDemo.vue';
// import store from '../store/index2.js';
import { mapState } from 'vuex' //这里调用
export default {
     components: {
      MyDemo
     },
    computed: {
      ...mapState({
        name: state => state.name,
        address(state){
          return state.address;
        }
      })
    },   
    data(){
        return{
            msg:'test7777',
            abc:'55555',
            countnum:0 ,
            num:88888,
            count:8
        }
    },
    methods:{
        // fangfayi(vale){
        //    this.abc=vale
        //  }
        testdemo(){
           // store.commit("addnum",10)//同步
          //  this.countnum=store.state.count
          console.log(this.$store.state.name)
        }
    }
}
</script>
复制代码

如果index.js换作其他文件明会报错!

 

 

 

 参考:https://vuex.vuejs.org/zh/guide/structure.html

 

 

参考:https://www.cnblogs.com/samve/p/10726629.html

 

 

如果直接引用js

 import store from '../store/index.js';
 
可以这样用

 

 main.js 中store 也可以注释

 

 

 

posted @   剧里局外  阅读(348)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示