VueJS-渲染功能

我们已经看到了组件及其用法。例如,我们有一个需要在整个项目中重复使用的内容。我们可以将其转换为组件并将其使用。

让我们看一个简单组件的示例,看看render函数必须在其中做什么。

<html>
   <head>
      <title>VueJs - Web176教程网/https://www.web176.com</title>
      <script type = "text/javascript" src = "/demo/vue/vue2.min.js"></script>
   </head>
   <body>
      <div id = "component_test">
         <testcomponent></testcomponent>
      </div>
      <script type = "text/javascript">
         Vue.component('testcomponent',{
            template : '<h1>Hello World</h1>',
            data: function() {
            },
            methods:{
            }
         });
         var vm = new Vue({
            el: '#component_test'
         });
      </script>
   </body>
</html>

考虑上面的示例简单示例,该示例可打印Hello World。

现在,如果要重用该组件,可以通过再次打印来实现。例如,

<div id = "component_test">
   <testcomponent></testcomponent>
   <testcomponent></testcomponent>
   <testcomponent></testcomponent>
   <testcomponent></testcomponent>
</div>

输出将是以下内容:

Hello World Hello World Hello World Hello World

但是,现在我们需要对该组件进行一些更改。我们不希望打印相同的文本。我们如何改变它?如果我们在组件内部输入内容,是否会考虑?

让我们考虑以下示例,看看会发生什么。

<div id = "component_test">
   <testcomponent>Hello Jai</testcomponent>
   <testcomponent>Hello Roy</testcomponent>
   <testcomponent>Hello Ria</testcomponent>
   <testcomponent>Hello Ben</testcomponent>
</div>

输出结果与我们之前看到的相同,它不会根据需要更改文本。

Tips:组件确实提供了一些称为slot的东西。让我们利用它,看看是否能达到预期的效果。

<html>
   <head>
      <title>VueJs - Web176教程网/https://www.web176.com</title>
      <script type = "text/javascript" src = "/demo/vue/vue2.min.js"></script>
   </head>
   <body>
      <div id = "component_test">
         <testcomponent>Hello Jai</testcomponent>
         <testcomponent>Hello Roy</testcomponent>
         <testcomponent>Hello Ria</testcomponent>
         <testcomponent>Hello Ben</testcomponent>
      </div>
      <script type = "text/javascript">
         Vue.component('testcomponent',{
            template : '<h1><slot></slot></h1>',
            data: function() {
            },
            methods:{
            }
         });
         var vm = new Vue({
            el: '#component_test'
         });
      </script>
   </body>
</html>

如上面的代码所示,在模板中我们添加了插槽,因此现在需要使用值在组件内部发送。大家可以试试运行下效果,可以输出我们想要的数据。

Hello Jai Hello Roy Hello Ria Hello Ben

作者:terry,如若转载,请注明出处:https://www.web176.com/vuejs/989.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2020年11月4日 上午11:35
下一篇 2020年11月4日 下午3:06

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注