vuex核心API使用用例

html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vuex-demotitle>
    <script src="libary/vue.js">script>
    <script src="libary/vuex.js">script>
head>
<body>
<div id="app">
    <h1>{{ msg }}h1>
    <Counter ref="aa">Counter>
    <div> {{ userName }}div>
    <button @click="add">+button>
    <button @click="minus">-button>
    <button @click="ride">xbutton>
    <button @click="updateName">变名字button>
    <button @click="getUserName">得到用户名button>
div>
<script>
    const Counter = {
        template : `
            
{{ count }}
{{ name }}
`, computed : { count(){ return this.$store.state.count; }, name() { return this.$store.state.name; }, getUserName() { return this.$store.getters.userName; } } }; const store = new Vuex.Store({ state : { count : 10, name : 'Jack' }, getters : { userName (state) { return 'Hello,'+ state.name; } }, mutations : { increment (state) { state.count ++; }, decrement (state) { state.count --; }, getRide (state) { state.count = state.count*state.count; }, updateName (state,name) { state.name = state.name === 'Jack' ? name : 'Jack'; } }, actions : { getRides (context) { context.commit('getRide'); } } }); new Vue({ el: '#app', store, data: { msg : 'Hello Vuex', userName:'', }, components: { Counter }, methods : { add() { this.$store.commit('increment'); }, minus() { this.$store.commit('decrement'); }, updateName() { this.$store.commit('updateName','qi.huang'); }, ride(){ this.$store.dispatch('getRides'); }, getUserName(){ this.userName = this.$refs.aa.getUserName; } } }); script> body> html>

你可能感兴趣的:(vue)