首页 > 编程 > JavaScript > 正文

Vuex 使用 v-model 配合 state的方法

2019-11-19 12:31:38
字体:
来源:转载
供稿:网友

v-model 最好用的就是配合 data 成 Two-way Binding,但若使用 Vuex 之後,是否能使用 v-model 搭配 state Two-way Binding 呢 ?

Version

Vue 2.5.17

Vuex 3.0.1

V-model vs. Data

HelloWorld.vue

<template> <div>  <div>   <input type="text" v-model="name">  </div>  <div>   {{ name }}  </div> </div></template><script>/** data */  const data = function() { return {  name: '', };};export default { name: 'HelloWorld', data,};</script>

Vue 的 v-model 法,直接 <input> 定到 name data。

Value vs. Input

但若 name data 提升到 Vuex 的 name state 之後,就了。

Vuex 的是 Unidirection Dataflow, state 只能被取,要入 state 必靠 mutation ,因此 v-model 法直接入 state 。

v-model 本是 value property binding input event 的 syntatic sugar,因此可以回基本作,使用 value input 。

HelloWorld.vue

<template> <div>  <div>   <input type="text" :value="name" @input="onInputName">  </div>  <div>   {{ name }}  </div> </div></template><script>import { mapState } from 'vuex';/** computed */const computed = mapState(['name']);/** methods */const onInputName = function(e) { this.$store.commit('setName', e.target.value);};const methods = { onInputName,};export default { name: 'HelloWorld', computed, methods,};</script>

第 4 行

<input type="text" :value="name" @input="onInputName">

name 定到 value , onInputName() 定到 input event。

16 行

const computed = mapState(['name']);

name state 建立 name computed。

19 行

const onInputName = function(e) { this.$store.commit('setName', e.target.value);};

onInputName() ,接收 input event,呼叫 setName mutations 修改 name state。

store.js

import Vue from 'vue';import Vuex from 'vuex';Vue.use(Vuex);/** state */const state = { name: '',};/** mutations */const setName = (state, payload) => state.name = payload;const mutations = { setName,};export default new Vuex.Store({ strict: true, state, mutations,});

很的 Vuex 法,由 setName mutation 修改 name state。

法然可行,但似乎失了原本 v-model 的特色,又必走回路使用 event

V-model vs. Computed with Setter

HelloWorld.vue

<template> <div>  <div>   <input type="text" v-model="name">  </div>  <div>   {{ name }}  </div> </div></template><script>/** computed */const name = { get() {  return this.$store.state.name; }, set(value) {  this.$store.commit('setName', value); },};const computed = { name,};export default { name: 'HelloWorld', computed,};</script>

第 4 行

<input type="text" v-model="name">
v-model 回了,但定的是 name computed,而不是 name data。

14 行

const name = { get() {  return this.$store.state.name; }, set(value) {  this.$store.commit('setName', value); },}

建立 name computed,了 v-model 能作,特 name computed 加上 setter。

  • get() : name state 抓料
  • set() :呼叫 setName mutation 入 state

透有 setter 的 computed,我就能使用 v-model 了。

Conclusion

然使用 value vs. input 法也行,但 v-model vs. computed with setter 法更雅,上建用此

Sample Code

完整的例可以在我的 GitHub 上找到

Reference

Vuex , Form Handling

总结

以上所述是小编给大家介绍的Vuex 使用 v-model 配合 state的方法 ,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表