5-vue语法 v-html和v-bind

288 阅读1分钟

v-html可以解析html标签

在小程序中直接写html标签不会被解析,要写在v-html中才可以

<template>
  <view>
    <view v-html="code"></view>
    <h2>uniapp课程</h2>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        code: "<h1>uniapp课程</h1>"
      };
    }
  }
</script>

<style lang="scss">

</style>

第二行的代码是写的h2标签,没有被解析,第一行的代码是通过v-html解析的,可以正常显示

image.png

[还可以用如下方法写]

实际上vue就是把v-html指令转换成如下代码在浏览器中显示的

<view class="">
   <rich-text nodes="<h1>uniapp课程</h1>"></rich-text>
</view>

image.png

在微信开发者工具中可以看到被转换的代码,rich-text在uniapp的文档中,组件--富文本中可以看到 image.png

[v-bind 动态绑定标签属性]

要把自定义的属性写到标签中去,能正常解析,就要用v-bind绑定,v-bind的简写是一个冒号 加了属性绑定的标签属性里,只能是js变量

<template>
  <view>
    <view v-html="code"></view>
    <h2>uniapp课程</h2>
    <view class="">
      <rich-text nodes="<h1>uniapp课程</h1>"></rich-text>
    </view>
    
    -------
    
    <image :src="img"></image>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        img:"../../static/images/pic1.jpg"
      };
    }
  }
</script>

<style lang="scss">
.out{
  .row {
    font-size: 50rpx;
  }
}
</style>

如果直接把img写到src里面去是不行的,不能解析,要用v-bind绑定才行

image.png

###[动态的将图片渲染到页面]

使用属性绑定和循环一起结合,将三张图都渲染到页面中

<template>
  <view>
    <image :src="img"></image>
    <image :src="'../../static/images/pic'+item+'.jpg'" mode="" v-for="item in [1,2,3]"></image>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        img:"../../static/images/pic1.jpg"
      };
    }
  }
</script>

<style lang="scss">
.out{
  .row {
    font-size: 50rpx;
  }
}
</style>

image.png