在Vue中,可以使用mixin将store添加到组件中。下面是一个示例:

首先,创建一个store.js文件来定义store对象和相关的state、mutations、actions等内容:

// store.js
export default {
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  },
  actions: {
    increment(context) {
      context.commit('increment');
    }
  }
}

然后,在需要使用store的组件中,通过mixin引入store:

// MyComponent.vue
import store from './store.js';

export default {
  mixins: [store],
  computed: {
    count() {
      return this.$store.state.count;
    }
  },
  methods: {
    increment() {
      this.$store.dispatch('increment');
    }
  }
}

在上面的示例中,我们通过mixin将store对象添加到组件中。然后,可以在computed属性中使用this.$store.state.count来获取state中的count值,在methods中使用this.$store.dispatch('increment')来调用action中的increment方法。

注意,需要在Vue实例中引入store对象,例如:

// main.js
import Vue from 'vue';
import App from './App.vue';
import store from './store.js';

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

这样,store就能在组件中正常使用了

vue的mixin怎么写store

原文地址: https://www.cveoy.top/t/topic/iysU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录