14_vue组件data.html 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <div id="app">
  10. <h1>num1:{{num1}}</h1>
  11. <!-- 组件中的变量只能在组件的模板中使用 -->
  12. <h1>num2:{{num2}}</h1>
  13. <h1 @click="clickFun">这是一个vue实例的h1标题</h1>
  14. <box></box>
  15. </div>
  16. <template id="box-temp">
  17. <div>
  18. <h1>{{num2}}</h1>
  19. <h1 @click="clickHandle">这是一个组件的h1标题</h1>
  20. </div>
  21. </template>
  22. <script src="./js/vue.js"></script>
  23. <script>
  24. new Vue({
  25. el: '#app',
  26. data:{
  27. num1:10
  28. },
  29. methods:{
  30. clickFun(){
  31. console.log("父组件h1被点击了");
  32. this.num1++;
  33. }
  34. },
  35. components:{
  36. "box":{
  37. // 组件data是一个函数且返回一个对象
  38. data(){
  39. return{
  40. num2:20
  41. }
  42. },
  43. template:"#box-temp",
  44. methods:{
  45. clickHandle(){
  46. console.log("子组件h1被点击了");
  47. this.num2++;
  48. }
  49. }
  50. }
  51. }
  52. })
  53. </script>
  54. </body>
  55. </html>