(7)Vue基础6-Vuex

Vuex是一套组件状态管理维护的解决方案。形象的说有一个商店用来存储各个组件的数据,每个组件可以从商店中获取数据,避免组件间传值的困难。

注意:在实例化vue的内容中,想要在DOM结构中获取,一般是通过$name获取的,如$el、$data。

(1)使用:Vuex的使用可以直接通过script标签直接在head中引入。

引用代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>vuex状态管理器</title>
    <script type="text/javascript" src="./vue/vue.js"></script>
    <script type="text/javascript" src="./vue/vuex.js"></script>
</head>
<body>
<div class="wrap">
    <div id="app">
        <p>{{this.$store.state.name}}</p>
    </div>
</div>
<script type="text/javascript">
    var store = new Vuex.Store({
        state:{
            name:"vue.js"
        }
    })

    var vm = new Vue({
        el:"#app",
        store
    })
</script>
</body>
</html>
View Code

在使用state的数据中,要使用$store.state.name调用,一般使用的较多的话,可以使用计算属性,将数据进行封装(store中的数据是响应式的,调用状态可以使用computed中返回)。

computed返回数据:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>vuex状态管理器computed</title>
    <script type="text/javascript" src="./vue/vue.js"></script>
    <script type="text/javascript" src="./vue/vuex.js"></script>
</head>
<body>
<div class="wrap">
    <div id="app">
        <p>{{name}}</p>
    </div>
</div>
<script type="text/javascript">
    var store = new Vuex.Store({
        state:{
            name:"vue.js,通过computed返回!"
        }
    })
    var vm = new Vue({
        el:"#app",
        store,
        computed:{
            name(){
                return this.$store.state.name
            }
        }
    })
</script>
</body>
</html>
View Code

如果数据是多个时,一般会使用mapState辅助函数(数据映射)来生成计算属性:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>vuex状态管理器computed</title>
    <script type="text/javascript" src="./vue/vue.js"></script>
    <script type="text/javascript" src="./vue/vuex.js"></script>
</head>
<body>
<div class="wrap">
    <div id="app">
        <p>{{name}}</p>
        <p>{{pass}}</p>
    </div>
</div>
<script type="text/javascript">
    var store = new Vuex.Store({
        state:{
            name:"vue.js,通过computed+Vuex.mapState返回!",
            pass:"我是密码"
        }
    })
    var vm = new Vue({
        el:"#app",
        store,
        computed:Vuex.mapState({
            //键key:计算属性的名称
            //值value:函数,将state数据返回
            name: state => state.name,
            pass:state => state.pass    
        })
    })
</script>
</body>
</html>
View Code

 

posted @ 2020-12-19 19:16  壹碗  阅读(123)  评论(0)    收藏  举报