There are many pages in a program, and a lot of data on multiple pages are also shared, so we need to extract these shared pages. These data are managed by Vuex.
First, you need to install vuex dependencies
. Select manual configuration when creating:
After selecting the route and installing Vuex
, the store/index.js file appears in the project
//放置全局状态
state: {
},
//计算属性
getter:{
},
//修改数据/状态的方法methods
mutations: {
},
//异步修改数据
actions: {
},
//vuex细分模块
modules: {
}
Click the button to increase the age:
//放置全局状态
state: {
username:"wangchen",
age:17
},
//计算属性
getters:{
xuAge:function(state){
return state.age + 1
}
},
//修改数据/状态的方法methods
mutations: {
addAge(state,payload){
state.age += payload
}
},
//异步修改数据
actions: {
},
//vuex细分模块
modules: {
}
<template>
<div class="about">
<h1>This is an about page</h1>
<h1>姓名:{
{
$store.state.username}}</h1>
<h1>年龄:{
{
$store.state.age}}</h1>
<h2>虚岁:{
{
$store.getters.xuAge}}</h2>
<button @click="addAge">添加</button>
</div>
</template>
<script>
export default{
mounted(){
console.log(this); //打印查找如何获取组件
},
methods:{
addAge:function(){
this.$store.commit('addAge',3) //调用addAge方法,每次传入参数3
}
}
}
The action requests asynchronous data and renders it on the page:
//异步修改数据
actions: {
//去请求提供段子的服务器
getJoke(context){
let httpUrl = 'https://api.apiopen.top/getJoke?paga=1&count=10&type=text'
fetch(httpUrl).then((res)=>{
//第一次获取的是响应数据,是json结构,需要进行处理
return res.json()
}).then((res)=>{
console.log(res)
context.commit('getList',res.result)
})
}
},
Find rendering elements:
<template>
<div class="about">
<ul>
<li v-for="(item,i) in $store.state.list" :key="i">
<h3>{
{
item.name}}</h3>
<p>{
{
item.text}}</p>
</li>
</ul>
</div>
</template>
<script>
export default{
mounted(){
console.log(this);
//触发vuex的action方法
this.$store.dispatch('getJoke')
},
}
</script>