<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