简体   繁体   English

有什么方法可以使用 mustache 语法将参数传递给 Vue.JS 中的绑定变量

[英]Is there any way to pass parameters to a binded variable in Vue.JS with moustache syntax

Let's say i have an HTML of the form:假设我有一个表单的 HTML:

<div>
  {{ GREETING_MESSAGE_FROM_TO }}
</div>

And in my data:在我的数据中:

data() {
  return {
      GREETING_MESSAGE_FROM_TO: 'Hello this message is for {{variable_1}} from {{variable_2}}'
  }
}

My question is that is there any way to pass the variables for this template dynamically from within the html.我的问题是有什么方法可以从 html 中动态传递此模板的变量。 Looking for something similar in Angular.. Something like this format:在 Angular 中寻找类似的东西.. 像这样的格式:

<div>
  {{ GREETING_MESSAGE_FROM_TO | [variable_1, variable_2] }}
</div>

I would simply use a method since variables are not being computed:我会简单地使用一种方法,因为没有计算变量:

methods:{
   GREETING_MESSAGE_FROM_TO(variable_1, variable_2){
      return `Hello this message is for ${variable_1} from ${variable_2}`
   }
}

In your template :在您的模板中:

<div>
  {{ GREETING_MESSAGE_FROM_TO(props1, props2) }}
</div>

If those variable are needed to be computed then choose computed instead of methods hook.如果需要计算这些变量,则选择计算而不是方法挂钩。

There are 3 ways:有3种方式:

data() {
  return {
      variable_1: 'Sam',
      variable_2: 'Alex',
      GREETING_MESSAGE_FROM_TO: `Hello this message is for ${this.variable_1} from ${this.variable_2}'
  }
}

or better solution:或更好的解决方案:

data() {
  return {
      variable_1: 'Sam',
      variable_2: 'Alex'
  }
},
computed() {
      GREETING_MESSAGE_FROM_TO: `Hello this message is for ${this.variable_1} from ${this.variable_2}'
}

and

<div>
  {{ GREETING_MESSAGE_FROM_TO }}
</div>

note that when variable_1 or 2 changes, the greeting updates automatically.请注意,当 variable_1 或 2 更改时,问候语会自动更新。

but you can use methods too:但你也可以使用方法:

methods: {
      GREETING_MESSAGE_FROM_TO: function (variable_1, variable_2) {
          return `Hello this message is for ${variable_1} from ${variable_2}'
    }
}

with this usage这种用法

<div>
  {{ GREETING_MESSAGE_FROM_TO('Sam', 'Alex') }}
</div>

or reactive data as args.或反应数据作为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM