1.vue3.x过滤器
vue3.x是不再支持过滤器了,已经将器移除了。取而代之的是:计算属性,方法
vue过滤器
2.计算属性
<template>
<h1>数据源:{{username}}</h1>
<button @click="changzhangs">修改username</button>
<h1>计算属性:{{fullName1}}</h1>
<h2>计算属性2:{{fullName2}}</h2>
</template>
<script>
import { defineComponent, computed, reactive, watch, ref, watchEffect } from 'vue';
export default defineComponent({
inheritAttrs: false,
name: '我是一个儿子组件',
setup(){
const username = reactive({
firstName: '东方',
lastName: '不败'
});
// 计算属性1,
const fullName1 = computed(() => {
return username.firstName + '---' + usernaem.lastName;
})
// 计算属性2
const fullName2 = computed({
set(){
console.log('修改了了')
},
get(){
return username.firstName + '---' + usernaem.lastName;
}
})
return {
username,
fullName1,
fullName2
}
}
})
</script>
或者是使用方法
<template>
<div>
{{messageChange()}}
</div>
<button @click="changeName">
修改name
</button>
</template>
<script>
export default {
// setup() {
// const name = '张三';
// return {
// name
// }
// },
data(){
return {
name: '张三'
}
},
methods: {
messageChange() {
return '$' + this.name
},
changeName() {
this.name = '修改了的'
}
}
}
</script>
但是那全局的过滤器怎么办,如果在应用中全局注册了过滤器,那么在每个组件中用计算属性或方法调用来替换它可能就没那么方便了。
取而代之的是,你可以通过全局属性以让它能够被所有组件使用到:
import { createApp } from 'vue'
// import Vue from 'vue'
import App from './App.vue'
const app = createApp(App)
app.config.globalProperties.$filters = {
currencyUSD(value) {
// alert(999)
console.log('修改零零')
return '$' + value;
}
}
app.mount('#app');
// 全局的计算属性
使用
```vue
<template>
<p>{{ $filters.currencyUSD(accountBalance) }}</p>
</template>