你能夠用 v-model 指令在表單<input>
、<textarea>
及<select>
元素上建立雙向數據綁定。它會根據控件類型自動選取正確的方法來更新元素。儘管有些神奇,但 v-model 本質上不過是語法糖。它負責監聽用戶的輸入事件以更新數據,並對一些極端場景進行一些特殊處理。v-model 會忽略全部表單元素的 value、checked、selected attribute 的初始值而老是將 Vue 實例的數據做爲數據來源。你應該經過 JavaScript 在組件的 data 選項中聲明初始值。app
綁定數據:函數
<input v-model="message" placeholder="edit me"> <p>Message is: {{ message }}</p>
案例:this
<!--子組件--> <template> <div> <!--綁定數據--> <input v-model="rumenz" /> <span> {{rumenz}} </span> <button @click="cleanVal">清除數據</button> </div> </template> <script> export default{ //將函數聲明成一個屬性 props:['cleanVal1'], data(){ return{ rumenz:"入門小站" } }, methods: { cleanVal(){ this.rumenz=""; } } } </script> <!--父組件--> <template> <div id="app"> {{msg}} <button @click="cleanVal">父組件清空</button> <!--將子組件的cleanVal1的函數變量綁定到cleanVal函數上--> <ModelBind ref="child" :cleanVal1="cleanVal"/> </div> </template> <script> import ModelBind from "./components/ModelBind" export default { name: 'App', data() { return { msg: "hello 入門小站" } }, methods: { cleanVal(){ //父組件操做子組件的函數 this.$refs.child.cleanVal(); } }, components: { ModelBind //必須聲明 } } </script> <style> </style>