Svelte

# 視頻教程

http://noover.leanapp.cn/courses

# 安裝(Install)

npm install -g svelte-cli

# 創建一個會說你好世界的組件(HelloWorld Component)

  • 新建一個項目文件夾,新建一個 HelloWrold.html 內容如下。
<!-- HelloWrold 組件 -->
<h1>你好 {{name}}</h1>
  • 使用命令編譯 html 文件
svelte compile --format iife HelloWorld.html > HelloWorld.js
  • 創建 index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Svelte Application</title>
</head>
<body>
    
    <application></application>
    
    <script src="./HelloWorld.js"></script>
    <script>
      var app = new HelloWorld({
        target: document.querySelector( 'application' ),
        data: {
          name: '世界'
        }
      });
    </script>
</body>
</html>

# 組件實例方法(Component API)

創建一個組件的實例的方法就是通過 new 調用并傳入配置項

  • 要加載到的 DOM 節點上面
target: document.querySelector( 'main' )
  • 組件的初始數據
data: {
    author: {
      name: '近藤麻理惠'
      gender: 'female'
      nationality: 'Japan'
    },
    title: '怦然心動人生整理魔法'
    recommendedReason: '勤儉持家,人人有責。無論男女,統統要干。'
}

# 在我們的 HelloWorld 例子中,在你的Chrome 控制臺輸入以下內容

以下內容都是實例的方法,每次開始測試之前可以刷新一下,清空之前的變量。

# get

app.get('name')
// "世界"

# set

app.set({ name: '天地' })

# observe

observe 字面上的意思就是觀察,在代碼中的意思就是觀察 name,當值改變的時候就執行回調函數。

可以看到加上觀察就立馬觸發了回調,打印了當前 name 的值

const observer = app.observe( 'name', name => {
  console.log( `當前 name 的值是 ${name}` );
});

app.set({name:'虛空大帝'})

observer.cancel() // 取消觀察

app.set({name:'皓月大帝'})

傳入{ init: false } 那么第一次就不會觸發

app.observe( 'name', ( newValue, oldValue ) => {
  console.log( `長度對比 ${newValue.length > oldValue.length ? 'new > old' : 'new < old'}` );
}, { init: false });

app.set({name:'宵元大帝~'})

默認所有回調會在更新前完成,傳入{ defer: true } 會導致回調在組件更新完成之后調用。
這樣的操作組要是跟 Dom 有關聯,所以我們需要添加一點代碼來驗證它們。

  • HelloWorld.html
<h1>你好 {{name}}</h1>

<canvas id="canvas-container" width="{{ canvas_width }}" height="{{ canvas_height }}"></canvas>

<style type="text/css">
    #canvas-container{
        background: #7F7BFF;
    }
</style>
  • 重新編譯一下
svelte compile --format iife HelloWorld.html > HelloWorld.js
  • index.html
  var app = new HelloWorld({
    target: document.querySelector( 'application' ),
    data: {
      name: '世界',
      canvas_width: '350',
      canvas_height: '150'
    }
  });

  function redraw(newValue, oldValue) {
    const canvas = document.querySelector('#canvas-container')
    console.log("Dom height " + canvas.height);
    console.log("Dom width " + canvas.width);
    console.log(newValue + "  -> " + oldValue);
  }

  app.observe('canvas_width', redraw, { init: false})
  app.observe('canvas_height', redraw, { defer : true, init: false })
  • 在控制臺里面輸入
app.set({ canvas_height: 20 })
app.set({ canvas_width: 20 })

# on

on 在 js 語言中通常監聽某一事件,這很符合慣例

const listener = app.on( 'eat', event => {
  console.log( `${event.name} 超齡兒童,你老婆叫你回家吃晚飯了` );
});

# fire

觸發某一事件

app.fire( 'eat', {
  name: 'Alex'
});
  • teardown

刪除 DOM 會觸發這個事件

app.on( 'teardown', () => {
  alert( '滾蛋吧 組件君!' ); 
});

app.teardown()

# HelloWorld 組件源碼分析

  • NeedTodo

# 組件模板語法(Template syntax)

# 變量

使用小胡子Mustaches語法輸出變量

<p>{{a}} + {{b}} = {{a + b}}</p>
<h1 style='color: {{color}};'>{{color}}</h1>

# 條件

{{#if user }}
    <div>{{ user.name }} is beautful girl!</div>
{{/if}}
{{#if x > 10}}
  <p>{{x}} 大于 10</p>
{{elseif 5 > x}}
  <p>{{x}} 小于 5</p>
{{else}}
  <p>{{x}} 在 5 與 10 之間</p>
{{/if}}

# 循環

<h1>水果大家庭</h1>

<ul>
  {{#each fruits as fruit}}
    <li>{{fruit}}</li>
  {{/each}}
</ul>
fruits: ['蘋果','梨','香蕉','葡萄','橘子','菩提','火龍果','荔枝']

# 指令

<p>Count: {{count}}</p>
<button on:click='set({ count: count + 1 })'>+1</button>

# 組件樣式(Style)

<canvas id="canvas-container" width="{{ canvas_width }}" height="{{ canvas_height }}"></canvas>


<style type="text/css">
    #canvas-container{
        background: #7F7BFF;
    }
</style>

# 組件行為(Script)

# 組件屬性

<p>Count: {{count}}</p>
<button on:click='set({ count: count + 1 })'>+1</button>

<script>
  export default {
    data () {
      return {
        count: 0
      };
    }
  };
</script>

# 計算屬性

<p>
  The time is
  <strong>{{hours}}:{{minutes}}:{{seconds}}</strong>
</p>

<script>
  export default {
    data () {
      return {
        time: new Date()
      };
    },

    computed: {
      hours: time => time.getHours(),
      minutes: time => time.getMinutes(),
      seconds: time => time.getSeconds()
    }
  };
</script>

# 生命周期

<script>
  export default {
    onrender () {
      this.interval = setInterval( () => {
        this.set({ time: new Date() });
      }, 1000 );
    },

    onteardown () {
      clearInterval( this.interval );
    },

    data () {
      return {
        time: new Date()
      };
    },

    computed: {
      hours: time => time.getHours(),
      minutes: time => time.getMinutes(),
      seconds: time => time.getSeconds()
    }
  };
</script>

# 幫助函數

把你需要的函數放到 helpers 里面那就可以在模板中使用了,但是必須是純函數。

<p>
  The time is
  <strong>{{hours}}:{{leftPad(minutes, 2, '0')}}:{{leftPad(seconds, 2, '0')}}</strong>
</p>

<script>

  function leftPad(str, len, ch) {
      str = str + '';

      len = len - str.length;
      if (len <= 0) return str;

      if (!ch && ch !== 0) ch = ' ';
      ch = ch + '';

      return ch.repeat(len) + str;
  };
    
  export default {
    helpers: {
      leftPad
    },

    onrender () {
      this.interval = setInterval( () => {
        this.set({ time: new Date() });
      }, 1000 );
    },

    onteardown () {
      clearInterval( this.interval );
    },

    data () {
      return {
        time: new Date()
      };
    },

    computed: {
      hours: time => time.getHours(),
      minutes: time => time.getMinutes(),
      seconds: time => time.getSeconds()
    }
  };
</script>

# 組件方法

<button on:click='say("hello")'>say hello!</button>

<script>
  export default {
    methods: {
      say ( message ) {
        alert( message ); 
      }
    }
  };
</script>

# 組件事件

記得在你的 data 上添加 done 變量
node 就是當前的 dom 節點,callback 就是我要執行的代碼,自行打印一下就很清楚了。

<button on:longpress='set({ done: true })'>click and hold</button>

{{#if done}}
  <p>clicked and held</p>
{{/if}}

<script>
  export default {
    events: {
      longpress ( node, callback ) {
        function onmousedown ( event ) {
          const timeout = setTimeout( () => callback( event ), 1000 );

          function cancel () {
            clearTimeout( timeout );
            node.removeEventListener( 'mouseup', cancel, false );
          }

          node.addEventListener( 'mouseup', cancel, false );
        }

        node.addEventListener( 'mousedown', onmousedown, false );

        return {
          teardown () {
            node.removeEventListener( 'mousedown', onmousedown, false );
          }
        };
      }
    }
  };
</script>

# 子組件

此小節注意大小寫,組件用大寫,別弄錯了。

  • 創建一個新的文件 Widget.html
<div class="widget-container">
    <h1>hei! Widget</h1>
</div>
  • 編譯一下
svelte compile -f iife -i Widget.html -o Widget.js
  • 給 HelloWrold 添加一下代碼
import Widget from './Widget.html';

export default {
    components: {
        Widget
    },
    ......
}
  • 編譯一下 HelloWorld.html
svelte compile -f iife HelloWorld.html > HelloWorld.js
  • 在給 index.html 修改一下代碼
    Widget 由于被 HelloWorld 依賴所以需要先加載
    <script src="./Widget.js"></script>
    <script src="./HelloWorld.js"></script>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容