vue vuex开启严格模式和演示错误代码

新建vue项目

 main.js

import Vue from 'vue'
import App from './App.vue'
import store from "@/store";

Vue.config.productionTip = false;

new Vue({
  render: h => h(App),
  store
}).$mount('#app');

app.vue

<template>
  <div id="app">
    <h1>根组件
      - {{ $store.state.title }}
      - {{ $store.state.count }}
      -- {{ title }}
      -- {{ count }}
    </h1>
    <input type="text">
    <son-a></son-a>
    <hr>
    <son-b></son-b>
  </div>
</template>

<script>
import SonA from "@/components/SonA"
import SonB from "@/components/SonB"
import { mapState} from 'vuex'

export default {
  name: 'App',
  components:{
    SonA,
    SonB
  },
  computed:{
    ...mapState(['count','title'])
  },
  created() {
    //检查vuex是否安装成功
    console.log(this.$store);
    console.log(this.$store.state.count);
  }
}
</script>

<style>

</style>

index.js

//存放是vuex的相关代码
import Vue from 'vue'
import Vuex from 'vuex'
//插件安装
Vue.use(Vuex);
//创建仓库
const store = new Vuex.Store({
    //通过state可以提供数据
    //严格模式,上线时需要关闭,否则影响性能
    strict:true,
    state:{
        title:'仓库大标题',
        count:100
    }
});

//导出给main.js使用
export default store;

//获取store
// 1 this.$store
// 2 import 导入 store

//模板中 {{ $store.state.xxx}}
//组件逻辑中 this.$store.state.xxx
//js模板中 store.state.xxx

SonA.vue

<template>
    <div class="box">
        <h2>SonA子组件</h2>
        从Vuex中获取的值: <label for="">{{ $store.state.count }}</label>
        <br>
        <button @click="handleAdd">值 + 1</button>
    </div>
</template>

<script>
    export default {
        name: "SonA",
        methods:{
            handleAdd(){
                //错误代码,不可以这样使用
                //this.$store.state.count++


            }
        }
    }
</script>

<style scoped>
    .box{
        border: 2px solid #cccccc;
        width: 400px;
        padding: 10px;
        margin: 20px;
    }


</style>

SonB.vue

<template>
    <div class="box">
        <h2>SonB子组件</h2>
        从vuex中获取的值:<label for="">{{ count }}</label>
        <br>
        <button>值 - 1</button>
    </div>
</template>

<script>
    import { mapState } from 'vuex'

    export default {
        name: "SonB",
        computed:{
            ...mapState(['count'])
        }
    }
</script>

<style scoped>
    .box{
        border: 2px solid #cccccc;
        width: 400px;
        padding: 10px;
        margin: 20px;
    }


</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虾米大王

有你的支持,我会更有动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值