riot.js教程【五】标签嵌套、命名元素、事件、标签条件

前文回顾
riot.js教程【四】Mixins、HTML内嵌表达式
riot.js教程【三】访问DOM元素、使用jquery、mount输入参数、riotjs标签的生命周期;
riot.js教程【二】组件撰写准则、预处理器、标签样式和装配方法;
riot.js教程【一】简介;html

标签嵌套

让咱们定义一个父标签account,一个子标签subscriptionjquery

<account>
  <subscription  plan={ opts.plan } show_details="true" />
</account>

<subscription>
  <h3>{ opts.plan.name }</h3>

  // Get JS handle to options
  var plan = opts.plan,
      show_details = opts.show_details

  // access to the parent tag
  var parent = this.parent

</subscription>

注意:show_details的命名方式,这里不能写成驼峰式的名字,由于浏览器解析标签的时候会把大写转成小写浏览器

接下来咱们把account标签添加到页面的body中dom

<body>
  <account></account>
</body>

<script>
riot.mount('account', { plan: { name: 'small', term: 'monthly' } })
</script>

父标签的参数是经过riot.mount方法传递的,子标签的参数是经过标签属性传递过去的ide

注意:嵌套的标签老是在父标签内部声明,定义;this

标签内嵌入HTML

咱们先定义一个my-tag标签code

<my-tag>
  <p>Hello <yield/></p>
  this.text = 'world'
</my-tag>

注意:这里有一个yield占位符,咱们稍后再讲它orm

如今咱们在页面上使用这个标签htm

<my-tag>
  <b>{ text }</b>
</my-tag>

那么他渲染出来以后,是以下这个样子的:对象

<my-tag>
  <p>Hello <b>world</b><p>
</my-tag>

你看到了吗?yield占位符输出的,实际上是text变量

这就是在标签内嵌入HTML代码

命名元素

当元素具有ref属性的时候,

这个元素会被连接到this.refs上,

这样你就能够很方便的用JS访问到它

<login>
  <form ref="login" onsubmit={ submit }>
    <input ref="username">
    <input ref="password">
    <button ref="submit">
  </form>

  // grab above HTML elements
  submit(e) {
    var form = this.refs.login,
        username = this.refs.username.value,
        password = this.refs.password.value,
        button = this.refs.submit
  }

</login>

注意,这个指向的操做,是在mount事件被触发前完成的,因此你能够在mount事件中访问到this.refs

事件

DOM事件能够直接和riotjs标签内的方法绑定,示例以下:

<login>
  <form onsubmit={ submit }>

  </form>

  // this method is called when above form is submitted
  submit(e) {

  }
</login>

只要事件名以on开头的,好比:onclick, onsubmit, oninput,均可以直接绑定方法

这类事件也能够直接绑定一句表达式,以下:

<form onsubmit={ condition ? method_a : method_b }>

在事件方法内,this指代本标签实例,方法执行完以后,会立刻执行this.update()事件,

若是你在方法内部,使用了event.preventUpdate,那么方法执行完以后,就不会执行this.update()事件;

方法的第一个参数就是标准的event对象

  • e.currentTarget 指代触发事件的DOM元素
  • e.target 也指代触发事件的DOM元素
  • e.which 指代按键代码 (keypress, keyup, 等).

标签条件

你可使用标签条件来决定是否须要显示一个标签,以下:

<div if={ is_premium }>
  <p>This is for premium users only</p>
</div>

注意,标签条件的值能够是一个变量,也能够是一个表达式

除了if以外,还可使用show和hide来决定是否显示一个标签

show – 当值是true的时候,至关于 style="display: ''"

hide – 当值是true的时候,至关于 style="display: none"

if – 当值是true的时候,会把该标签加入到DOM元素中,是false的时候,不会把标签加入到dom元素中

相关文章
相关标签/搜索