vue3使用vuex

  • Post author:
  • Post category:vue


第一步安装:

package.json

{

“name”: “demo”,

“version”: “0.1.0”,

“private”: true,

“scripts”: {

“serve”: “vue-cli-service serve”,

“build”: “vue-cli-service build”,

“lint”: “vue-cli-service lint”

},

“dependencies”: {

“core-js”: “^3.6.5”,

“vue”: “^3.0.0”,

“vue-router”: “^4.0.0-0”,


“vuex”: “^4.0.0-0”

},

“devDependencies”: {

“@vue/cli-plugin-babel”: “~4.5.0”,

“@vue/cli-plugin-eslint”: “~4.5.0”,

“@vue/cli-plugin-router”: “~4.5.0”,

“@vue/cli-plugin-vuex”: “~4.5.0”,

“@vue/cli-service”: “~4.5.0”,

“@vue/compiler-sfc”: “^3.0.0”,

“babel-eslint”: “^10.1.0”,

“eslint”: “^6.7.2”,

“eslint-plugin-vue”: “^7.0.0-0”

}

},

第二步:

在main.js中引入

import { createApp } from ‘vue’

import App from ‘./App.vue’

import router from ‘./router’


import store from ‘./store’

createApp(App).

use(store).

use(router).mount(‘#app’)

第三步 /store/index.js


import { createStore } from ‘vuex’

// VueX数据管理框架

// VueX 创建了一个全局唯一的仓库,用来存放全局的仓库

export default createStore({


state: { name: ‘zhangsan’ },

// mutations 里面只允许写同步代码,不允许写异步代码

// commit 和 mutations做关联

mutations: {


changeName(state, str) {


state.name = str;


}

},

// dispatch 和 actions 做关联

actions: {


getData(store) {


store.commit(‘changeName’, ‘hello’)


}

}

})

第四步页面获取和修改vuex数据

<template>

<div class=”about”>

<h1

@click=”handleClick”

>This is an about page</h1>

<h1>{

{name}}</h1>

</div>

</template>

<script>

import { toRefs } from ‘vue’;

// 引入useStore方法


import { useStore } from ‘vuex’;

export default {

name: ‘Home’,

setup() {


const store = useStore();


const { name } = toRefs(store.state);


const handleClick = () => { // 修改vuex里面的数据


store.dispatch(‘getData’)


}

return { name, handleClick }

}

}

</script>



版权声明:本文为xyphf原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。