Estoy tratando de hacer un componente usando Vue para mi código javascript pero no funciona. Mi objetivo principal es crear un componente con vue o Vue3
<head> <title></title> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> </head <body> <div id="app"> <myelement name="ibrahim" age="12"></myelement> </div> </body> <script> Vue.component("myelement",{ props:["name","age"], // for arguments template:` <h1> welcome to my vue component,<br> name :{{name }} and age : {{age}}</h1> `// template where my code template should be }) var vm = new Vue({ // creating an object from Vue el:"#app" // bind my created code to the id "app" }) </script>Este código funciona, pero cuando coloco un código Javascript en lugar de un código html. tengo un error
este código lo estoy usando para mi código Javascript, pero el vue no está llamando a mi código javascript. Solo está llamando a mi código html.
<head> <title></title> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> </head <body> <h3>this page works</h3> <div id="app"> <myelement ></myelement > </div> </body> <script> document.write("<h1>Header from document.write()</h1>"); var temp = "<h1>Hello from vue veriable</h1>" Vue.component("myelement ",{ template:` <script> alert(1); document.write("<h1>Header from document.write()</h1>"); </script> `// template where my code template should be }) var vm = new Vue({ // creating an object from Vue el:"#app" // bind my created code to the id "app" }) </script>lo que quiero hacer es, cuando creo la etiqueta en la página, aparecerá la alerta (1).
En vue, no puede usar la etiqueta de script en la plantilla de componentes y obtiene el siguiente error:
[Advertencia de Vue]: error al compilar la plantilla: las plantillas solo deben ser responsables de asignar el estado a la interfaz de usuario. Evite colocar etiquetas con efectos secundarios en sus plantillas, como
<script>, ya que no se analizarán.
En su lugar, puede poner sus códigos javascript en el enlace del ciclo de vida created . Este gancho se llama cuando su componente crea:
<head> <title></title> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> </head> <body> <h3>this page works</h3> <div id="app"> <myelement></myelement> </div> </body> <script> Vue.component("myelement", { template: `<h2>Hello</h2>`, }); var vm = new Vue({ el: "#app", created() { alert(1); document.write("<h1>Header from document.write()</h1>"); }, }); </script>No estoy seguro, pero creo que este código funcionará correctamente:
<head> <title></title> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> </head> <body> <h3>this page works</h3> <div id="app"> <myelement :message="variableAtParent"></myelement> </div> </body> <script> Vue.component("myelement", { props: ['message'], template: '<p>At child-comp, using props in the template: {{ message }}</p>',, }); var vm = new Vue({ el: "#app", data: { variableAtParent: 'DATA FROM PARENT!' } }); </script>