vue.js - 将选定的值传递给 vuejs 函数

标签 vue.js

如何将选定的值传递给 vuejs 函数? v-model 我猜不会有帮助。

之后我需要为过滤器设置值 项目:项目 | orderBy sortKey 反转 其中 reversesortKey 是动态值。

html

<select class="sort-filter" v-on="change: sortBy(???)">
  <option value="title asc">Title (A-Z)</option>
  <option value="title desc">Title (Z-A)</option>
  <option value="price asc">Price (Min. - Max.)</option>
  <option value="price desc">Price (Max. - Min.)</option>
</select>

js

  methods: {
    sortBy: function (sortKey) {
      console.log(sortKey)
    }
  }

最佳答案

您有多种方法可以做到这一点。

编辑:改进 2)

可以像 2) 一样使用 v-model,但是您可以使用 computed properties 而不是直接在 orderBy 过滤器中使用值

computed: {
    sortKey: {
        get: function() {
            return this.sorting.split(' ')[0]; // return the key part
        }
    },
    sortOrder: {
        get: function() {
            return this.sorting.split(' ')[1]; // return the order part
        }
    }
}

这样,sortKey 和 sortOrder 将像过滤器中的普通属性一样可用:

v-repeat="items | orderBy sortKey sortOrder"

1)使用javascript事件:

如果不指定任何参数,将自动传递原生事件对象

<select class="sort-filter" v-on:change="sortBy">

然后你可以像这样使用它:

methods: {
    sortBy: function(e) {
        console.log(e.target.value);
    },
}

2) 使用 v-model

您可以添加 v-model 指令

<select name="test" v-model="sorting" v-on:change="sortBy">

这样 sorting 值将在每次更改时更新。

您可以在 ViewModel 的数据对象中添加此值以更加清晰:

data: {
  sorting: null // Will be updated when the select value change
}

然后您可以像在您的方法中一样访问该值:

methods: {
    sortBy: function() {
        console.log(this.sorting);
    },
}

如果你只是需要更新sortKey的值,这个方法就没有必要了。

3)其他奇怪的方式

您显然可以将模型值用作参数。

<select name="test" v-model="sortKey" v-on:change="sortBy(sortKey)">

这是可行的,但我真的不明白这一点。

methods: {
    sortBy: function(sortKey) {
        console.log(sortKey);
    },
}

关于vue.js - 将选定的值传递给 vuejs 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31272276/

相关文章:

vue.js - 在没有 mapState 的情况下调用 vuex store

vue.js - VueJS - 有没有办法有条件地应用转换?

vue.js - Element UI 使用默认主题

javascript - 基于计算属性数组的 Vuejs 输入绑定(bind)

vue.js - Vue-apollo 不填充数据对象

javascript - VueJS 在嵌套的 v-for 循环中动态添加表单组件?

javascript - V-for 每 2 项添加行给我错误的索引

mysql - GET http://localhost:3000/server/server.js net::ERR_ABORTED 404(未找到)

vue.js - 如何使用vite和yarn创建vue项目

javascript - [Vue警告] : Error in event handler for "upload-success": "TypeError: fns.apply is not a function"