学习记录
Nuxt+Vuex初体验
小呀嘛小二郎,背着书包上学堂。。。今天一个困扰了我一周时间的问题终于被我解决了,值得庆祝在Nuxt中使用Vuex实现数据存储首先:在store目录下新建一个index.js文件需要有两个组件(index || demo)[组件名自定]一、在store目录下新建一个index.js文件index.js内容如下//定义数据export const sta...
2019-12-22 04:58:41
132
                <p>小呀嘛小二郎,背着书包上学堂。。。</p> 

今天一个困扰了我一周时间的问题终于被我解决了,值得庆祝

在Nuxt中使用Vuex实现数据存储

 首先:

在store目录下新建一个index.js文件

需要有两个组件(index || demo)[组件名自定]

 

一、在store目录下新建一个index.js文件

index.js内容如下

//定义数据
export const state = () => ({
  count: 1  //定义count初始值为1
})

//定义方法
export const mutations = {
inc (state) {
state.count++
},
deinc(state){
state.count--
}
}


二、需要有两个组件

 index.vue内容如下:

<template>
  <div>
    <h1>{{ count }}</h1>   <!--count是计算属性中的count-->
    <button @click="inc">增加</button>   
    <NuxtLink to="/demo">Demo</NuxtLink>
  </div>
</template>

<script>
//使用解构赋值从vuex中引入需要的state,也可以引入mapMutations...
import { mapState } from "vuex";

export default {
computed: mapState(["count"]),//计算属性,count是在store中的index.js中定义的state
methods: {
inc() {
this.$store.commit("inc");//触发store中的index.js中定义的mutations中的inc方法
}
}
};
</script>

demo.vue内容如下:

<template>
    <div>
      <h1>{{ $store.state.count }}</h1> <!--取出store中state的count-->
      <button @click="deinc">减少</button>
      <NuxtLink to="/">Home</NuxtLink>
  </div>
</template>

<script>
export default {
methods:{
deinc:function () {
this.$store.commit('deinc') //触发store中mutations中的deinc方法
}
}
}
</script>


三、最终效果如下


 这个东西我竟然研究了一星期,可笑。。。

注意:所有的路由跳转均采用<nuxt-link to=""></nuxt-link>,切忌使用<a href=""></a>血的教训。。。