简体   繁体   English

我可以在 Vue js 中对函数进行数据绑定吗?

[英]Can I data bind a function in Vue js?

is it possible to data bind a function in Vue?是否可以在 Vue 中对函数进行数据绑定?

In the template I have something like: <title> {{nameofFunction()}}</title>在模板中我有类似的东西: <title> {{nameofFunction()}}</title>

When I run it, it just says native function on the page.当我运行它时,它只是在页面上显示本机功能。

Thanks.谢谢。

There is also such thing as " computed property " in Vue, designed to do exactly this: Vue 中还有诸如“计算属性”之类的东西,旨在做到这一点:

<template>
  <div id="example">
    <p>Original message: "{{ message }}"</p>
    <p>Computed reversed message: "{{ reversedMessage }}"</p>
  </div>
</template>

<script>
export default {
  data:() => ({
    message: 'Hello'
  }),
  computed: {
    // a computed getter
    reversedMessage: function () {
      // `this` points to the vm instance
      return this.message.split('').reverse().join('')
    }
  }
}
</script>

yes you can.是的你可以。 Could you share how are you defining your data options?您能否分享一下您是如何定义数据选项的?

Here I have an example that works both in Vue2 and Vue3这里我有一个适用于 Vue2 和 Vue3 的示例

<template>
  <div id="app">
    <h1>{{messageHelloFn()}}</h1>
  </div>
</template>

<script>
export default {
  data() {
    return {
      messageHelloFn: (name = 'Lucas') => {
        return `Hello ${name}`
      }
    };
  }
};
</script>

Live example: https://codepen.io/LucasFer/pen/abywRMW现场示例: https ://codepen.io/LucasFer/pen/abywRMW

a.js一个.js

const func = (str) => str
export default fn
<template>
  <div id="app">
    <div v-for="item in items">
      {{ getTime(item) }}
    </div>
    <div>
      {{ fn('a') }}
    </div>
    <div>
      {{ func('b') }}
    </div>
  </div>
</template>

<script>
import func from './a.js'
export default {
  data () {
    return {
      items: ['123123', '456456'],
      fn: (str) => str
    }
  },
  methods: {
    getTime (v) {
      return v + '123'
    }
  }
};
</script>

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

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