Vue.js-4.資料綁定

Vue.js-3.資料綁定

 

選項物件屬性:

  • data

v-text  (綁定一般字串資料)

v-html (綁定含html標籤)

v-model(雙向綁定)

 


 

data

資料型態 : objectfunction

但如元件檔(.vue)為各自獨立非共用,所以元件中的data只能是function型態

例:

index.html

 <div id="myapp">{{message}}</div>

v-text

這邊也可以使用 v-text 接資料

<div id="myapp">
      <span v-text="message"></span>
</div>

但較有彈性作法是用大括號

<div id="myapp">
      <span>{{message}}</span>
</div>

https://jsfiddle.net/YiruAtStudio/e4809f6t/5/

main.js

var myapp = new Vue({
  el: '#myapp',
  data: {
    message: 'Hello myapp!'
  }
})
console.log(myapp.message)

https://jsfiddle.net/YiruAtStudio/01kdp57w/6/


如果是在元件中的data只能是function

例:

src\components\mytest.vue

<div class="myfont">
        {{mymsg}}
</div>
<script>
export default{
  data () {
    return {
      mymsg: 'hi,mymsg!'
    }
  }
}
</script>


v-html

如果要返回的是html,則使用v-html

index.html

<div id="myapp">
 <span v-html="message"></span>
</div>

main.js

var myapp = new Vue({
  el: '#myapp',
  data: {
    message: '<a href="#">我是超連結</a>'
  }
})
console.log(myapp.message)

https://jsfiddle.net/YiruAtStudio/sx35fd9m/


v-model

index.html

<div id="myapp">
  姓名:<input type ="text" v-model="myname">
  購買數量:<input type = "number" v-model="mynum">
  <br>
  {{myname}},購買數量為:{{mynum}}
</div>

main.js

var myapp = new Vue({
  el: '#myapp',
  data: {
    myname: 'Name:',
    mynum: '5'
  }
})

console.log(myapp.myname)

https://jsfiddle.net/YiruAtStudio/8vex0af1/


表單資料綁定

index.html

<input type ="text" v-model="myname">
<input type = "number" v-model="mynum">
<textarea v-model="mynote"></textarea>
運送:<br>
<input type ="radio" name="s1" v-model="transport" value="711">7-11<br>
<input type ="radio" name="s1" v-model="transport" value="family">全家<br>
<input type ="radio" name="s1" v-model="transport" value="hilife">萊爾富<br>
加購:<br>
<input type="checkbox" v-model="chkbox" value="python">python
<input type="checkbox" v-model="chkbox" value="Java">Java
<input type="checkbox" v-model="chkbox" value="PHP">PHP
付款方式:
<select v-model="select_item">
  <option value="ATM">ATM</option>
  <option value="pay">貨到付款</option>
  <option value="ment">取貨付款</option>
</select>
{{myname}},購買數量為:{{mynum}},<br>
{{mynote}}。<br>
運送方式{{transport}}<br>
加購{{chkbox}}<br>
付款方式{{select_item}}

main.js

var myapp = new Vue({
  el: '#myapp',
  data: {
    myname: 'Name:',
    mynum: '5',
    mynote: '備註',
    transport: '請選擇',
    // 宣告checkbox-data中的變數為陣列[]
    chkbox:[],
    //也可宣告null
    select_item:null,
  }
})

https://jsfiddle.net/YiruAtStudio/8vex0af1/4/


參考:

https://ithelp.ithome.com.tw/articles/10194175

Yiru@Studio - 關於我 - 意如