将所选值传递给vuejs函数

rma*_*002 15 vue.js

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

我需要在item: items | orderBy sortKey reverse where 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>
Run Code Online (Sandbox Code Playgroud)

JS

  methods: {
    sortBy: function (sortKey) {
      console.log(sortKey)
    }
  }
Run Code Online (Sandbox Code Playgroud)

Nee*_*ule 28

你有几种方法可以做到这一点.

编辑:改进2)

可以像在2)中一样使用v模型,但不是直接在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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

v-repeat="items | orderBy sortKey sortOrder"
Run Code Online (Sandbox Code Playgroud)

1)使用javascript事件:

如果未指定任何参数,则将自动传递本机事件对象

<select class="sort-filter" v-on:change="sortBy">
Run Code Online (Sandbox Code Playgroud)

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

methods: {
    sortBy: function(e) {
        console.log(e.target.value);
    },
}
Run Code Online (Sandbox Code Playgroud)

2)使用v模型

您可以添加v-model指令

<select name="test" v-model="sorting" v-on:change="sortBy">
Run Code Online (Sandbox Code Playgroud)

这样sorting,每次更改时都会更新该值.

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

data: {
  sorting: null // Will be updated when the select value change
}
Run Code Online (Sandbox Code Playgroud)

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

methods: {
    sortBy: function() {
        console.log(this.sorting);
    },
}
Run Code Online (Sandbox Code Playgroud)

如果您只需要更新该sortKey值,则甚至不需要此方法.

3)其他奇怪的方式

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

<select name="test" v-model="sortKey" v-on:change="sortBy(sortKey)">
Run Code Online (Sandbox Code Playgroud)

这是有效的,但我没有看到这一点.

methods: {
    sortBy: function(sortKey) {
        console.log(sortKey);
    },
}
Run Code Online (Sandbox Code Playgroud)


小智 5

如果您想使用动态值循环并且不能使用 v-model,这应该可以工作

<select name="option" v-on:change="selectedOption($event.target.value)">
    <option value="0">SELECT</option>
    <option v-for="i in 10" :value="i">{{ i }}</option>
</select>
Run Code Online (Sandbox Code Playgroud)