【问题标题】:Vue: The best practice to change value in the component nested in the Vue Router using VuexVue:使用 Vuex 更改嵌套在 Vue Router 中的组件中的值的最佳实践
【发布时间】:2022-01-01 16:28:42
【问题描述】:

我是 Vue、Vue Router 和 Vuex 的新手。

请建议使用 Vuex 存储更改/更新嵌套在 Vue 路由器中的组件中的值的最佳做法。 我编写了一个简单的代码,通过点击按钮来更改组件中的数字,但似乎无法正常工作。

以下是我制作的代码:

// Trying to change the value in the component, 
// but not updating the DOM, only the value in the state
function incrementValueInComponent(){
    store.commit('increment');
    alert("number in the store is: " + store.state.testNumber);
}

// *** Vuex store ***
const store = new Vuex.Store({
    state: {
        testNumber: 0
    },
    mutations: {
      increment (state) {
        state.testNumber++
      }
    }
});

// *** Component and Vue router ***
const Foo = { 
    store:store,
    data(){
        return {
            myNumber:this.$store.state.testNumber
        }
    },
    template: '<div>{{myNumber}}</div>' ,
}
const routes = [
  { path: '/', component: Foo }
]
const router = new VueRouter({
  routes
})

const app = new Vue({
  router
}).$mount('#app')
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- Vue, Vuex, Vue router-->
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <script src="https://unpkg.com/vuex"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
    <div id="app">
        <h1>Hello App!</h1>
        <p>
          <router-link to="/">Top Page</router-link>
        </p>
        <router-view></router-view>
        <button class="btn" onclick="incrementValueInComponent()">Increment Number</button>
    </div>
    <script src="javascript.js"></script>
</body>
</html>

我做错了什么还是这种方法违背了 Vue 的概念? 任何意见,将不胜感激。提前致谢。

【问题讨论】:

    标签: javascript vue.js vuex vue-router


    【解决方案1】:

    使用computed

    const Foo = { 
        store:store,
        computed: {
            myNumber () {
                return this.$store.state.testNumber
            }
        }
        template: '<div>{{myNumber}}</div>' ,
    }
    

    【讨论】:

      猜你喜欢
      • 2017-03-17
      • 2021-06-05
      • 2021-04-06
      • 2021-01-30
      • 2021-06-10
      • 2018-03-10
      • 2019-08-14
      • 2019-02-07
      • 2020-10-11
      相关资源
      最近更新 更多