BUI 屬性與值綁定

2020-08-12 14:09 更新

案例

案例截圖

1. 屬性動(dòng)態(tài)綁定

b-bind 綁定支持2種數(shù)據(jù)格式. 并且通過 bs.title="XXX" 或者 bs.attrs.title="xxx" 可以觸發(fā)屬性的修改. 綁定的字段在 data 里面

  • Object : 鍵值為樣式名,值為布爾值
  • String : 值為樣式名

  1. var bs = bui.store({
  2. scope: "page",
  3. data: {
  4. title: "這是動(dòng)態(tài)標(biāo)題",
  5. attrs: {
  6. "title": "這是動(dòng)態(tài)標(biāo)題",
  7. "data-title": "自定義標(biāo)題",
  8. }
  9. }
  10. })

html:

  1. <!-- 綁定多個(gè) -->
  2. <p b-bind="page.attrs">綁定title屬性,及自定義屬性</p>
  3. <!-- 綁定1個(gè) -->
  4. <p b-bind="page.title">綁定title屬性</p>

效果預(yù)覽

查看效果

2. 值的動(dòng)態(tài)綁定

有三種值的設(shè)置, 推薦 b 標(biāo)簽作為默認(rèn)的雙向綁定標(biāo)簽. 如果內(nèi)容元素是塊狀, 可使用 div 標(biāo)簽.

  • b-text : 設(shè)置文本
  • b-html : 設(shè)置html
  • b-value : 設(shè)置屬性value,一般用于表單

  1. var bs = bui.store({
  2. scope: "page",
  3. data: {
  4. value: "Hello bui.js",
  5. attrs: {
  6. title: "這是動(dòng)態(tài)標(biāo)題",
  7. },
  8. title: "<h1>html標(biāo)題</h1>",
  9. }
  10. })

  1. <!-- 1.設(shè)置文本,支持對(duì)象 -->
  2. <b b-text="page.attrs.title"></b>
  3. <!-- 2.設(shè)置Html -->
  4. <div b-html="page.title"></div>
  5. <!-- 3.設(shè)置value -->
  6. <input b-value="page.value" class="bui-input"/>

效果預(yù)覽

案例截圖

查看效果

3. 靜態(tài)解析

靜態(tài)解析{{}}里面的值. 默認(rèn)沒有開啟, 如果需要, 初始化時(shí)設(shè)置 needStatic: true 才會(huì)解析. templates定義的模板方法里面不要使用{{}} 或者 b-開頭的模板命令.

  • 不支持表達(dá)式
  • 不支持動(dòng)態(tài)修改
  • 只在第一次渲染解析

  1. var bs = bui.store({
  2. scope: "page",
  3. data: {
  4. title: "這是動(dòng)態(tài)標(biāo)題2",
  5. attrs: {
  6. "title": "這是動(dòng)態(tài)標(biāo)題",
  7. "data-title": "自定義標(biāo)題",
  8. }
  9. },
  10. needStatic: true,
  11. })

html:

  1. <div title="{{page.attrs.title}}">{{page.title}}</div>

值得注意的是, 如果你的數(shù)據(jù)是公共數(shù)據(jù), isPublic:true 時(shí), needStatic不能為true,會(huì)干擾到路由, 那如何解析公共數(shù)據(jù)的{{}}值呢?

  1. window.router = bui.router();
  2. bui.ready(function() {
  3. // 公共數(shù)據(jù)
  4. window.store = bui.store({
  5. scope: "app",
  6. isPublic: true,
  7. data: {
  8. firstName: "Hello",
  9. lastName: "BUI"
  10. }
  11. })
  12. // 初始化路由
  13. router.init({
  14. id: "#bui-router",
  15. progress: true,
  16. hash: true,
  17. store: store,
  18. })
  19. })

store掛載到路由, 就可以解析公共數(shù)據(jù)的 {{app.firstName}} 之類的數(shù)據(jù), 在模塊里面,你也可以使用 store.firstName 讀取跟修改公共數(shù)據(jù)的值, 會(huì)在全局起作用, 比方商城的加入購物車.

注意, 如果是異步加載,比方TAB的動(dòng)態(tài)加載,你想要解析這個(gè) store 里面的模板的話, 需要在tab這個(gè)模塊里面執(zhí)行一次.

tab-setting.html

  1. <div b-text="app.firstName"></div>

tab-setting.js

  1. loader.define(function(){
  2. // tab-xxx 為當(dāng)前tab的樣式或id名稱.
  3. store.compile(".tab-setting");
  4. })
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)