state
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<!--
state是数据
Vuex中有一个构造函数是Store
我们想要创建vuex实例就需要new这个store
const store = new Vuex.Store({
state: {
}
})
const app = new Vue({
store
})
将store放入vue的配置对象后,该 store 实例会注入到根组件下的所有子组件中
在获取state中的值时,在组件中写computed
computed: {
数据名 () {
return this.$store.state.数据名
}
}
-->
</body>
</html>
getter
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>title</title>
</head>
<table>
</table>
<body>
<!--
getters中的所有getter都是函数
每个getter中都有一个state参数
每个getter中都有第二个参数getters
getter返回的除了数据以外还可以返回函数,这样可以通过传参的方式,得到对应的数据
getter直接返回的是数据,那么在使用时
computed: {
数据名 () {
return this.$store.getters.getter名
}
}
如果返回的是函数
computed: {
数据名 () {
return this.$store.getters.getter名(参数)
}
}
-->
</body>
</html>
mutation
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>title</title>
</head>
<table>
</table>
<body>
</body>
<script>
修改state只能用mutation去进行修改
mutations: {
mutation (state) {
// 因为mutation要修改state,所以他的第一个参数为state mutation想要被调用,需要在一些地方调用this.$store.commit('mutation')
}
}
// 触发mutation
store.commit('mutation')
大部分情况我们需要给mutation提交数据
store.commit('mutation', 数据)
那么在mutation的第二个参数中就是commit过来的数据
mutations: {
mutation (state, payload) {
payload就是commit过来的数据
}
}
</script>
</html>
action
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>title</title>
</head>
<table>
</table>
<body>
/*
action中就是专门完成异步请求的
发起请求,请求成功后commit(mutation, 请求结果)将数据发送给mutation
*/
</body>
</html>