简书链接:前端问题vue能否在template中调用方法呢?
文章字数:156,阅读全文大约需要1分钟
不能直接用,但是可以如下办法:computed

![9PAZX0[CSA_65C]$GFI_KFO.png](https://upload-images.jianshu.io/upload_images/2815884-b08e0a3df1934dc0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
vue2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <template> <div>{{ formattedDate }}</div> </template>
<script> export default { data() { return { date: new Date() }; }, computed: { formattedDate() { return this.formatDate(this.date); } }, methods: { formatDate(date) { return date.toLocaleDateString(); } } } </script>
|
vue3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| <template> <div> <p>原始值 a: {{ a }}</p> <p>原始值 b: {{ b }}</p> <p>计算后的和: {{ sum }}</p> </div> </template>
<script setup> import { ref, computed } from 'vue';
// 定义响应式数据 const a = ref(1); const b = ref(2);
const sum = computed(() => { return a.value + b.value; });
const publicProperties = { a, b, sum }; export { publicProperties }; </script>
|
option api
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| emplate> <div> <p>原始值 a: {{ a }}</p> <p>原始值 b: {{ b }}</p> <p>计算后的和: {{ sum }}</p> </div> </template>
<script> export default { data() { return { a: 1, b: 2 }; }, computed: {
sum() {
return this.a + this.b; } }, methods: {
incrementA() { this.a++; }, incrementB() { this.b++; } } }; </script>
|