<div id="counter"> Counter: {{ counter }} </div>
const Counter = { data() { return { counter: 0 } } } Vue.createApp(Counter).mount('#counter')
在 3.x 中,自定义组件上的 v-model 至关于传递了 modelValue prop 并接收抛出的 update:modelValue 事件:html
<ChildComponent v-model="pageTitle" /> <!-- 简写: --> <ChildComponent :modelValue="pageTitle" @update:modelValue="pageTitle = $event" />
若须要更改 model 名称,而不是更改组件内的 model 选项,那么如今咱们能够将一个 argument 传递给 model:vue
<ChildComponent v-model:title="pageTitle" /> <!-- 简写: --> <ChildComponent :title="pageTitle" @update:title="pageTitle = $event" />
除了像 .trim 这样的 2.x 硬编码的 v-model 修饰符外,如今 3.x 还支持自定义修饰符:
添加到组件 v-model 的修饰符将经过 modelModifiers prop 提供给组件。在下面的示例中,咱们建立了一个组件,其中包含默认为空对象的 modelModifiers prop。
请注意,当组件的 created 生命周期钩子触发时,modelModifiers prop 包含 capitalize,其值为 true——由于它被设置在 v-model 绑定 v-model.capitalize="bar"。api
<my-component v-model.capitalize="bar"></my-component>
app.component('my-component', { props: { modelValue: String, modelModifiers: { default: () => ({}) } }, template: ` <input type="text" :value="modelValue" @input="$emit('update:modelValue', $event.target.value)"> `, created() { console.log(this.modelModifiers) // { capitalize: true } } })
能够把一部分共用逻辑和数据写在一块来复用,好比本身项目中常常用的search方法加载列表就能够抽出来了app
//app.vue <template> <button @click="search"></button> </template> <script> import {getData} from "./api" import getSearchMethod from "./util.js" export default { setup(){//context 是一个普通的 JavaScript 对象,它暴露三个组件的 property:attrs,emit,slots var param = { page:1, size:10 } return getSearchMethod(param,getData); } } </script>
//api.js export const getData = function(){ return Promise.resolve({ list:['a','b'], total:2 }) }
//util.js import { ref } from 'vue' export const getSearchMethod = function(param,api){ param = ref(param); var total = ref(0); var tableData = ref([]); var search = ref(function(){ api(param.value).then(res=>{ total.value = res.total; tableData.value = res.list; }) }) return {param,total,tableData,search} }
将容器放到指定父容器下,咱们能够将它们嵌套在另外一个内部,以构建一个组成应用程序 UI 的树。this
<body> <div style="position: relative;"> <h3>Tooltips with Vue 3 Teleport</h3> <div> <modal-button></modal-button> </div> </div> </body>
app.component('modal-button', { template: ` <button @click="modalOpen = true"> Open full screen modal! (With teleport!) </button> <teleport to="body"> <div v-if="modalOpen" class="modal"> <div> I'm a teleported modal! (My parent is "body") <button @click="modalOpen = false"> Close </button> </div> </div> </teleport> `, data() { return { modalOpen: false } } })
在 Vue 3 中,组件如今正式支持多根节点组件,即片断编码
<!-- Layout.vue --> <template> <header>...</header> <main v-bind="$attrs">...</main> <footer>...</footer> </template>
destroyed 生命周期选项被重命名为 unmounted
beforeDestroy 生命周期选项被重命名为 beforeUnmount
移除$destroy 实例方法spa