zoukankan      html  css  js  c++  java
  • vue组件

    组件(Component)是 Vue.js 最强大的功能之一。

    组件可以扩展 HTML 元素,封装可重用的代码。

    组件系统让我们可以用独立可复用的小组件来构建大型应用,几乎任意类型的应用的界面都可以抽象为一个组件树

    <template>
      <div>如果不是为了衣锦返乡,谁愿意远走他乡。</div>
    </template>
    <script>

    我们看到组件中

    <template></template>
    组件中所有的内容都要在该语句中包含,当然,div 必须要有,根节点必须在DIV中,否则会出错

    创建好组件后,在APP.VUE中进行引用,并调用即可。

    <template>
      <div id="app">
        <img src="./assets/logo.png">
        <a/>//进行调用组件
      </div>
    </template>
    <script>
    import aa from './components/content'  //引用组件
    export default {
      name: 'App',
      components:{
    aa//注册组件
      }
    }
    </script>

    很简单的语法,多联系几次就明白了。


    父组件嵌套子组件
    1.创建obejce1.vue,child.vue组件

    父组件

    <template>
      <div>
        我是父组件
        <hr />
        <c ref="c"></c>
        <hr />
        <button @click="getMsg()">得到子组件的值</button>
        <hr />
        <button @click="getMessage()">父组件调用子组件的方法</button>
      </div>
    </template>
    <script>
    import c from "./child.vue";
    export default {
      data() {
        msg: "我是父组件中的值";
      },
      components: {
        c
      },
      methods: {
        getMsg() {
          alert(this.$refs.c.message);
        },
        getMessage() {
          this.$refs.c.getMessage();
        }
      }
    };
    </script>

    子组件

    从这里我们可以看到,和APP.VUE中的调用方式一样,多练习几次就可以了。


    父组件得到子组件中的值或调用子组件的方法
    父组件

    <template>
          <div>
            我是父组件
            <hr>
            <c ref="c">
            </c>
            <hr>
            <button @click="getMsg()">得到子组件的值</button>
            <hr>
            <button @click="getMessage()">父组件调用子组件的方法</button>
          </div>
        </template>
        <script>
        import c from "./child.vue";
        export default {
          data() {
            msg: "我是父组件中的值";
          },
          components: {
            c
          },
          methods:{
              getMsg(){
                  alert(this.$refs.c.message)
              },getMessage(){
                  this.$refs.c.getMessage();
              }
          }
        };
        </script>

    子组件:

    <template>
        <div>我是子组件</div>
    </template>
    <script>
    export default {
        data(){
            return{
                message:'我是子件中的值'
            }
        },methods:{
    getMessage(){
        alert('我是子组件中的方法');
    }
        }
    }
    </script>

    1.this.$refs.c.message
    2.this.$refs.c.getMessage();
    其实上面的关键字就是已经封装好的,直接调用即可,this代表在当前vue里,$refs代表一个引用,c就是我们注册的子组件名称,可以理解为一个对象,然后我们可以通过对象调用值,或方法。是不是和简单?按格式来就好,多练习几次就可以了。

  • 相关阅读:
    Python split分割字符串
    test markdown
    Python 数字格式转换
    Python 字符串改变
    Python axis的含义
    python 第三方库
    Spark快速入门
    vim快捷键
    Hadoop HDFS负载均衡
    YARN DistributedShell源码分析与修改
  • 原文地址:https://www.cnblogs.com/c546170667/p/11366843.html
Copyright © 2011-2022 走看看