Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

javascript - Vue md输入与Vuex仅在一个方向上更新(Vue md-input with Vuex updating only in one direction)

I have a Vue app with an input element bound to a like this:

(我有一个Vue应用,其输入元素绑定到一个这样的:)

<template>
   <input v-model="this.$store.state.myvalue"/>
</template>

and VueX store/index.js :

(和VueX store/index.js :)

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    myvalue: null
  },
  mutations: {},
  actions: {},
  modules: {}
});

When I modify myvalue with Vue devtools, the input's value changes too, but when I change the value in the input field, the state variable does not change.

(当我使用Vue devtools修改myvalue时,输入值也会更改,但是当我在输入字段中更改值时,状态变量不会更改。)

What am I doing wrong?

(我究竟做错了什么?)

I'm new to VueX.

(我是VueX的新手。)

  ask by retnikt translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Although it's not suggested to use vuex state directly bound with view layer, instead vuex is better to use for business logic, you can achieve changing the state on user input by below mentioned ways:

(尽管不建议使用直接与视图层绑定的vuex状态,但最好将vuex用于业务逻辑,但是您可以通过以下提到的方式来更改用户输入的状态:)

[1] two-way data binding: use v-model directive & bind the state in it.

([1]双向数据绑定:使用v-model指令并绑定其中的状态。)

On user input, the state will be updated.

(根据用户输入,状态将被更新。)

On changing state programmatically, the element's value will be updated & reflect on dom.

(以编程方式更改状态时,元素的值将更新并反映在dom上。)

.vue file

(.vue文件)

<template>
   <input v-model="this.$store.state.myvalue"/>
</template>

[2] manually create two-way data-binding.

([2]手动创建双向数据绑定。)

.vue file

(.vue文件)

<template>
   <input :value="this.$store.state.myvalue" @input="handleInput"/>
</template>

<script>
import {mapMutations} from 'vuex'

export default {
 methods: {
  handleInput (value) {
   this.UPDATE_MY_VALUE({ value })
  }
 }
}
</script>

store file

(储存档案)

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    myvalue: null
  },
  mutations: {
   UPDATE_MY_VALUE (state, { value }) {
    state.myvalue = value
   }
  },
  actions: {},
  modules: {}
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...