Javascript 从PHP到Vue.js获取动态数据
我正在使用PHP(CodeIgniter)呈现使用vue cli构建的页面 通常,如果我想将值从php传递到javascript,我会这样做:Javascript 从PHP到Vue.js获取动态数据,javascript,php,codeigniter,vue.js,Javascript,Php,Codeigniter,Vue.js,我正在使用PHP(CodeIgniter)呈现使用vue cli构建的页面 通常,如果我想将值从php传递到javascript,我会这样做: var page = '<?php echo $page ?>'; var页面=”; 但是由于页面是用vue构建的,所有的js都被缩小了,这一切都是不可能的。 我需要一个替代解决方案来获取从php发送的vue中的变量。试试这个:这里js变量msg2打印php变量$test value=“Chris” 例子 {{message}} {{m
var page = '<?php echo $page ?>';
var页面=”;
但是由于页面是用vue构建的,所有的js都被缩小了,这一切都是不可能的。
我需要一个替代解决方案来获取从php发送的vue中的变量。试试这个:这里js变量msg2打印php变量$test value=“Chris”
例子
{{message}}
{{msg2}}
var vue_det=新的vue({
el:“#简介”,
数据:{
消息:“我的第一个VueJS任务”,
msg2:“
}
});
您应该放弃传递var page=''的想法将>编码到JS中
1。检查您的路由-我假设您仍然有带有逻辑的PHP页面,并且Vue位于separate控制器上
$route['default_controller'] = 'Home';
// Create a new controller with the name Vue before adding the routes.
$route['vue'] = 'Vue'; // default page
$route['vue/(:any)'] = 'Vue/$1'; // vue/with-any-passing/value/you/want
2。控制器:Vue.php
<?php
class Vue extends CI_Controller {
public function index( $uri_for_vue = '' )
{
$vueSetup = array(
'settings' => array(
'vueURL'=> $uri_for_vue
)
);
$this->load->view('vueView', $vueSetup);
}
}
<html>
<head>
<title>vue page</title>
<script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
</head>
<body>
<div id = "intro" style = "text-align:center;">
<h1>{{ message }}</h1>
<p>{{ msg2 }}</p>
<?php
$test = "Chris";
?>
</div>
<script id='vue-elem' data-vue='<?php echo json_encode($settings)?>' type = "text/javascript"></script>
<script type = "text/javascript">
var vueElem = document.getElementById('vue-elem');
var vueSettings = JSON.parse(vueElem.getAttribute("data-vue"));
// you may want to remove the element from html after it's contents is loaded in js, or reset the
// vueElem .setAttribute("data-vue", "{}");
// you will want to add this line in the minified version so vue can self-load
var page = vueSettings.vueURL;
console.log('page url', page );
// now you can load vue
</script>
</body>
</html>
从组件调用API并填充数据。@devsiodera我不能。要调用API,我需要知道呈现为page/id
<html>
<head>
<title>vue page</title>
<script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
</head>
<body>
<div id = "intro" style = "text-align:center;">
<h1>{{ message }}</h1>
<p>{{ msg2 }}</p>
<?php
$test = "Chris";
?>
</div>
<script id='vue-elem' data-vue='<?php echo json_encode($settings)?>' type = "text/javascript"></script>
<script type = "text/javascript">
var vueElem = document.getElementById('vue-elem');
var vueSettings = JSON.parse(vueElem.getAttribute("data-vue"));
// you may want to remove the element from html after it's contents is loaded in js, or reset the
// vueElem .setAttribute("data-vue", "{}");
// you will want to add this line in the minified version so vue can self-load
var page = vueSettings.vueURL;
console.log('page url', page );
// now you can load vue
</script>
</body>
</html>