Options-based API
一个元件包含 properties/methods/optionsComposition API
一个元件封装逻辑到 function 中使用 ref
可以得到元素或是元件实体的参考,透过 ref()
这个function 建立! 结果会回传一个响应式的物件。
一样在 setup()
中使用 ref()
ex:
import { defineComponent, ref } from "vue";
export default defineComponent({
setup() {
const input = ref("");
return {
input,
};
},
});
原本在 Vue2 的写法
export default {
props: {
title: String
},
computed: {
vTitle() {
return '-' + this.title + '-';
},
itemsQuantity() {
return this.items.length;
}
},
data() {
return {
items: ['This', 'is'],
};
},
}
改用 Vue3 Composition API
import { ref, computed } from '@vue/composition-api';
export default {
props: {
title: String
},
setup(props) {
const vTitle = computed(() => '-' + props.title + '-');
const items = ref(['This', 'is']);
const itemsQuantity = computed(() => items.value.length);
return {
vTitle,
items,
itemsQuantity,
};
}
};
还可以利用 computed API,建立一个可读写的 ref 物件 (get & set function)
const count = ref(1)
const double = computed({
get: () => count.value * 2,
set: val => { count.value = val - 1 }
})
double.value = 3 // set: count.value = 3 - 1 = 2
console.log(count.value) // 2
console.log(double.value) // get: count.value * 2 = 4
原本 Vue2 写法
export default {
data() {
return {
items: ['This', 'is'],
append: ''
};
},
watch: {
items: {
handler: function(value, oldValue) {
this.append = '';
value.forEach(item => {
this.append += item + ' ';
});
},
immediate: true
}
},
}
Vue3中,使用新的 watch API 去异动
watch(source, callback, options)
import { ref, watch } from '@vue/composition-api';
export default {
setup(props) {
const items = ref(['This', 'is']);
const append = ref('');
watch(
// getter
() => items.value,
// callback
(items, oldItems) => {
append.value = '';
items.forEach(item => {
append.value += item + ' ';
});
},
// watch Options
{
lazy: false // immediate: true
}
)
return {
items,
append
};
}
};
每日一句:
每年都希望隔年花更多时间备稿
<<: [Day29] Scrum失败经验谈 – 没有经验的Scrum Master
广告优化除了要随时搭配工具监控数字之外,当然每个产品或是活动看的指标也都不尽相同,会给个建议: 每个...
点击特定物件是 E2E 中很常会做到的事,如果本身物件有设定好特定的 ID, Class 或 Att...
“Now I can look at you in peace; I don't eat you ...
CRM (Customer Relationship Management) 客户关系管理系统 Wh...
近年来软件业越来越风行,常常可以在网路上看到许多文章有着耸动的标题:「让你三个月成功转职年薪百万工程...